<template>
  <vxe-table :data="data" class="w-full" :max-height="560">
    <vxe-column title="平台" field="platform_name" minWidth="200"></vxe-column>
    <vxe-column title="店铺" field="shop_name" minWidth="150"></vxe-column>
    <vxe-column title="首选业务员" field="preferred_saleman_name" minWidth="100"></vxe-column>
    <vxe-column title="组织" field="first_level_department" minWidth="100"></vxe-column>
    <vxe-column title="操作" width="100">
      <template #default="{ rowIndex }">
        <el-button link type="primary" @click="data.splice(rowIndex, 1)">移除</el-button>
      </template>
    </vxe-column>
  </vxe-table>
  <div class="border flex w-full px-3 py-2 border-t-0 dark:border-gray-700">
    <el-cascader v-if="idsShow" clearable filterable :props="{ multiple: true }" :options="options" collapse-tags collapse-tags-tooltip class="w-60"
      @change="shopChange">
    </el-cascader>
    <el-button type="primary" plain class="ml-2" :disabled="!bindInfo.length" @click="handleAddShops">添加</el-button>
  </div>
</template>

<script setup>
const props = defineProps({
  modelValue: { type: Object, default: () => ({}) },
  options: { type: Array, default: () => ([]) },
})
const emit = defineEmits(['update:modelValue'])
const data = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})

const bindInfo = ref([])
const shopChange = (val = []) => {
  bindInfo.value = []
  val.forEach(d => {
    const [platform_id, shop_id] = d
    const item = props.options.find(o => o.value === platform_id)
    if (!item) return
    const obj = item.children.find(o => o.value === shop_id)
    if (!obj) return
    bindInfo.value.push({ ...obj, platform_id, shop_id })
  })
}

const idsShow = ref(true)
const handleAddShops = () => {
  bindInfo.value.forEach(d => {
    if (!data.value.some(b => b.shop_id === d.shop_id)) {
      data.value.push(d)
    }
  })
  bindInfo.value = []
  idsShow.value = false
  nextTick(() => {
    idsShow.value = true
  })
}

const init = () => {
  bindInfo.value = []
}

defineExpose({ init })
</script>